import Vue from 'vue';
import Vuex from 'vuex';
import { addCollect, cancelCollect } from '@/api/common';
import { Message } from 'element-ui'
Vue.use(Vuex);

const tokenInfoStorageKey = '__TOKEN_INFO__'
const store = {
  state: {
    tokenInfo: sessionStorage.getItem(tokenInfoStorageKey)
      ? JSON.parse(sessionStorage.getItem(tokenInfoStorageKey))
      : null,
    // userInfo.userType 1:超级管理员 2:管理员 3:专家 4:体验专家 5:会员, 6:体验会员, 7:普通用户 当前仅使用了3和4
    userInfo: sessionStorage.getItem("user")
      ? JSON.parse(sessionStorage.getItem("user"))
      : null,
  },
  getters: {
    token: (state) => state.tokenInfo ? state.tokenInfo.tokenValue : '',
    userInfo: (state) => state.userInfo,
  },
  mutations: {
    updateUserInfo(state, data) {
      state.userInfo = data
      sessionStorage.setItem('userId', data.userId)
      sessionStorage.setItem('user', JSON.stringify(data))
    },

    setToken(state, data) {
      state.tokenInfo = data
      sessionStorage.setItem(data.tokenName, data.tokenValue)
      sessionStorage.setItem(tokenInfoStorageKey, JSON.stringify(data))
    },

    logout(state) {
      state.tokenInfo = null
      state.userInfo = null
      sessionStorage.removeItem("satoken")      // 逐步替换掉
      sessionStorage.removeItem("userId")
      sessionStorage.removeItem("user")
      sessionStorage.removeItem(tokenInfoStorageKey)
    }
  },
  actions: {
    login({ commit }, data) {
      commit('updateUserInfo', data.user)
      commit('setToken', data.tokenInfo)
    },

    // 收藏功能
    // 使用示例1 this.$store.dispatch('setCollectStatus', { action: 'add', code: '070101', type: 2, name: "数学与应用数学"})
    // 使用示例2 this.$store.dispatch('setCollectStatus', { action: 'cancel', ids: [62] })
    setCollectStatus({ state }, data) {
      if (!state.userInfo) {
        return Message.error('请先登录')
      }
      if (data.action === 'add') {
        return addCollect({
          userId: state.userInfo.userId,
          ...data,
          action: undefined,
        }).then(res => {
          if (![0, 200].includes(res.code)) {
            Message.error(res.msg)
            return Promise.reject(res.msg)
          }
          Message.success('收藏成功')
          return res
        })
      } else if (data.action === 'cancel') {
        return cancelCollect(data.params).then(res => {
          if (![0, 200].includes(res.code)) {
            Message.error(res.msg)
            return Promise.reject(res.msg)
          }
          Message.success('已取消收藏')
        })
      }
    },
  },
  modules: {},
}
export default new Vuex.Store(store)
